#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
using namespace std;

int tickets = 1000; // 有 1000 张票

void* threadRoutine(void* args)
{
    int sum = 0;
    const char* name = static_cast<const char*>(args); 
    while(true)
    {
        // 如果票数 > 0 才能抢
        if(tickets > 0)
        {
            usleep(2000); // 耗时 2ms
            sum++;
            --tickets;
        }
        else
            break; // 没有票了

        usleep(2000); //抢到票后也需要时间处理
    }

    cout << "线程 " << name << " 抢票完毕，最终抢到的票数 " << sum << endl;
    delete name;
    return nullptr;
}

int main()
{
    pthread_t pt[5];
    for(int i = 0; i < 5; i++)
    {
        char* name = new char(16);
        snprintf(name, 16, "thread-%d", i);
        pthread_create(pt + i, nullptr, threadRoutine, name);
    }

    for(int i = 0; i < 5; i++)
        pthread_join(pt[i], nullptr);

    cout << "所有线程均已退出，剩余票数: " << tickets << endl;

    return 0;
}
